import React, { Component } from 'react';
import PropTypes from "prop-types";
import { View, Dimensions, TouchableHighlight, Image } from 'react-native'

import Label from '../label/index';
import Badge from '../badge/index';
import Slider from '../slider/index.js';
import Color from '../../config/theme/standard/color';
import FontSize from "../../config/theme/standard/fonts"

import {getSudokuStyle} from './SudokuStyle'
import Variables from '../../config/theme/styles/index';

export default class Sudoku extends Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            cellHeight: 80,
            isWideScreen: false
        };
        this._columnWidth = Math.ceil((props.rowWidth - 4 || Dimensions.get('window').width - 2) / props.columnCount)
    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    render() {
        let { rowCount, columnCount, slider, dataSource, dotColor,
            dotActiveColor, sliderAreaBgColor, dotStyle, rowWidth } = this.props;

        this._columnWidth = Math.ceil((this.props.rowWidth - 4 || Dimensions.get('window').width - 2) / this.props.columnCount)
        let { styles, SudokuStyle } = getSudokuStyle(Variables);
        //图标总数
        let cellsNum = dataSource.length;
        //每页显示数量
        let pageNum = rowCount * columnCount;
        //总页数
        let pageCount = Math.ceil(cellsNum / pageNum);

        let pageList = [];
        let pageTmp = [];
        for (let i = 0; i < pageNum * pageCount; i++) {
            if (i < cellsNum) {
                pageTmp.push(dataSource[i]);
            } else {
                pageTmp.push({});
            }
            if (pageTmp.length == pageNum) {
                pageList.push(pageTmp);
                pageTmp = [];
            }
        }

        let content = this._renderAll(dataSource);

        let itemHeight = this.state.cellHeight * rowCount + 2;

        if (slider && pageCount > 1) {
            let sliderData = [];

            for (let m = 0; m < pageList.length; m++) {
                let sudokuTmp = this._renderAll(pageList[m]);
                let tmp = { item: sudokuTmp, id: m };
                sliderData.push(tmp);
            }
            content = (
                <Slider
                    data={sliderData}
                    itemHeight={itemHeight}
                    pagination={true}
                    loop={false}
                    autoPlay={false}
                    isWidthCustom={true}
                    sliderWidth={rowWidth || Dimensions.get('window').width}
                    dotPosition={"outer"}
                    paginationBgColor={sliderAreaBgColor}
                    dotColor={dotColor}
                    dotActiveColor={dotActiveColor}
                    paginationDotStyle={dotStyle}
                />
            );
        }
        return (
            <View>
                {content}
            </View>
        )
    }

    _renderAll(dataSource) {
        let { styles,SudokuStyle} = getSudokuStyle(Variables);
        let { slider,columnCount } = this.props
        let conStyles = [styles.container];
        let cellBottom = 0;
        let flagTitle = false;
        if (this.props.hasOuterBorder) {
            if (this.props.hasInnerBorder) {
                conStyles.push({ borderTopWidth: 1 });
            } else {
                conStyles.push({ borderTopWidth: 1, borderBottomWidth: 1 });
            }

        }
        if (this.props.borderColor) {
            conStyles.push({ borderColor: this.props.borderColor });
        }
        dataSource.map((data)=>{
            if(data.title && data.title.length >=5){
                flagTitle = true
            }
        })
        if(columnCount == 5 && flagTitle){
            cellBottom = 10;
        }
        return (
            <View style={[conStyles, { width: (this._columnWidth + 0.25) * this.props.columnCount , backgroundColor: this.props.bgColor ,paddingBottom:cellBottom}]}>
                {this._renderCells(dataSource)}
            </View>
        );
    }

    _onPress(data) {
        if (this.props.onClick) {
            this.props.onClick(data);
        }
    }

    _cellLayout(event) {
        let cellHeight = event.nativeEvent.layout.height;
        if (cellHeight != this.state.cellHeight) {
            this.setState({ cellHeight });
        }
    }

    _getTextLength(text){
        let num = 0;
        var re = /^[a-z0-9]*$/i;
        for(var i=0;i<text.length;i++){
            if(re.test(text[i])){
                num = num + 0.5 
            }
        }               
        return num; 
    }

    _renderCells(dataSource) {
        let { styles,SudokuStyle} = getSudokuStyle(Variables); 
        const descriptionStyles = [styles.description];
        const titleStyles = [styles.title];
        const imageStyles = [styles.image];
        const cellStyles = [styles.cell];
        const { columnCount, hasTitle, hasDescription, hasInnerBorder, singleTitle,
            isHorizontal, cellHeight, imageStyle, borderColor, hasOuterBorder, rowHeight, cellStyle} = this.props;
        let sWidth = Dimensions.get('window').width
        let imgWidth ;
        if (imageStyle) {
            imgWidth = imageStyle.width
        }else{
            imgWidth = 26
        }
        if (cellHeight) {
            cellStyles.push({ height: cellHeight + 1 });
        }

        if (borderColor) {
            cellStyles.push({ borderColor });
        }

        return dataSource.map((data, index, dataList) => {

            let title = null;
            let description = null;
            let itemCount = dataSource.length;
            let borderBottom = 1;
            let borderLeft = 0;
            let borderRight = 1;
            let titleWidth = 0 ;
            let titleImgPadding = 0;
          

            if (hasOuterBorder) {
                if (!hasInnerBorder) {
                    borderBottom = 0;
                    borderRight = 0;
                } else {
                    if (index % columnCount == 0) {
                        if (this.props.rowWidth < sWidth) {
                            borderLeft = 1
                        }
                    }
                    if ((index % columnCount == 3 && columnCount == 4) || (index % columnCount == 2 && columnCount == 3) || (index % columnCount == 1 && columnCount == 2)) {
                        if (this.props.rowWidth < sWidth) {
                            borderRight = 1;
                        } else {
                            borderRight = 0;
                        }
                    }
                }
            } else {
                if (hasInnerBorder) {
                    if (itemCount % columnCount == 0) {
                        if (itemCount == columnCount) {
                            borderBottom = 0;
                        } else {
                            if (index > itemCount - columnCount - 1) {
                                borderBottom = 0;
                            }
                        }
                    }
                    else {
                        let row = Math.floor(itemCount / columnCount);
                        if (index > row * columnCount - 1) {
                            borderBottom = 0
                        }
                    }

                    if ((index % columnCount == 2 && columnCount == 3) || (index % columnCount == 3 && columnCount == 4) || (index % columnCount == 1 && columnCount == 2)) {
                        borderRight = 0;
                    }
                    if (itemCount - 1 == index) {
                        borderRight = 0;
                    }
                } else {
                    borderBottom = 0;
                    borderRight = 0;
                }
            }

            if (hasTitle) {
                title = (
                    <View style={titleStyles}>
                        <Label fontWeight={'500'} labelStyle={[{ fontSize: FontSize.sudoku.titleFontSize, }, data.titleStyle ? data.titleStyle : null]} text={data.title} numberOfLines={singleTitle ? 1 : 2} textAlign={'center'} color={data.color ? data.color : Color.sudoku.title} />
                    </View>
                );
                titleStyles.push({ marginTop: 2 });
            } 

            if( columnCount == 5 && data.title){
                const textLen =this._getTextLength(data.title);
                if(data.title.length >= 6 &&  this._columnWidth * columnCount <= 375){
                    titleWidth = 10;
                    titleImgPadding = 18
                }else if(data.title.length >= 6 ){
                    titleWidth = 20;
                    titleImgPadding = 18
                }else if(data.title.length == 5 && this._columnWidth * columnCount  <= 375 && this._columnWidth * columnCount >= 330 && textLen == 0.5){
                    titleWidth = 25;
                    titleImgPadding = 18
                }else if(data.title.length == 5 && this._columnWidth * columnCount  <= 375 && this._columnWidth * columnCount >= 330 && (textLen == 1||textLen == 1.5 || textLen ==2)){
                    titleWidth = 30;
                    titleImgPadding = 18
                }else if(data.title.length == 5 && this._columnWidth * columnCount  > 375 && textLen < 0.5){
                    titleWidth = 30;
                    if (this._columnWidth * columnCount  > 500 && this._columnWidth * columnCount < 800) {
                        titleImgPadding = 0
                    } else {
                        titleImgPadding = 18
                    }
                }else if(data.title.length == 5 &&  this._columnWidth * columnCount <= 330 && textLen <= 0.5){
                    titleWidth = 10;
                    titleImgPadding = 18
                }
            }
         
           
            if (hasTitle) { 
                if(columnCount == 5 && data.title && data.title.length >= 5){
                    title = (
                        <View style={[titleStyles,{width: this._columnWidth - titleWidth}]}>
                            <Label fontWeight={'500'} labelStyle={[{ fontSize: SudokuStyle.titleFontSize}, data.titleStyle ? data.titleStyle : null]} text={data.title}  textAlign={'center'} color={data.color ? data.color : SudokuStyle.titleColor} />
                        </View>
                    );
                }else{
                    title = (
                        <View style={titleStyles}>
                            <Label fontWeight={'500'} labelStyle={[{ fontSize: SudokuStyle.titleFontSize, }, data.titleStyle ? data.titleStyle : null]} text={data.title} numberOfLines={singleTitle ? 1 : 2} textAlign={'center'} color={data.color ? data.color : SudokuStyle.titleColor} />
                        </View>
                    );
                }
                titleStyles.push({ marginTop: 2 });
            } 

            if (columnCount == 3 || columnCount == 4 || columnCount == 5) {
                if (hasDescription) {
                    description = (
                        <View>
                            <View style={[descriptionStyles, { marginTop: 0 }]}>
                                <Label text={data.description1} numberOfLines={2} labelStyle={{ fontSize: FontSize.sudoku.descFontSize, color: Color.sudoku.desc }} textAlign={'center'} />
                            </View>
                            {
                                data.description2 ? <View style={descriptionStyles}>
                                    <Label text={data.description2} numberOfLines={2} textAlign={'center'} labelStyle={{ fontSize: FontSize.sudoku.descFontSize, color: Color.sudoku.desc }} />
                                </View> : null
                            }
                        </View>
                    );
                    cellStyles.push({ height: cellHeight + 25 });
                    if (columnCount == 4) {
                        descriptionStyles.push({ width: Dimensions.get('window').width / 4 - 30 });
                    } else if (columnCount == 5) {
                        descriptionStyles.push({ width: Dimensions.get('window').width / 5 - 30, });
                    }
                }
            }

            if (columnCount == 2 || (columnCount == 3 && isHorizontal)) {
                cellStyles.push({ flexDirection: 'row', height: rowHeight, justifyContent: 'flex-start' });
                if (columnCount == 2) {
                    cellStyles.push({ paddingLeft: 35 });
                } else {
                    cellStyles.push({ paddingLeft: 15 });
                }
                imageStyles.push({ width: 26, height: 26, marginHorizontal: 0, marginRight: 5 });
            }

            if (imageStyle) {
                imageStyles.push(imageStyle);
            }

            if (!isHorizontal && hasTitle) {
                imageStyles.push({ marginBottom: 8 });
            }

            if (data.showBadge == true) {
                let badgeArea = (
                    <View style={{ width: this._columnWidth }} >
                        <TouchableHighlight underlayColor={'transparent'} activeOpacity={0.8} disabled={data.disabled ? data.disabled : false} onPress={typeof data.onPress == 'function' ? data.onPress : () => this._onPress(data, index)}>
                            <View>
                                <View key={`cell-${(data.key != null) ? data.key : index}`} style={[cellStyles, cellStyle, { borderBottomWidth: borderBottom, borderLeftWidth: borderLeft, borderRightWidth: borderRight },]}>
                                    <Image source={data.icon} style={imageStyles} />
                                    {title}
                                    {description}
                                </View>
                            </View>
                        </TouchableHighlight>
                    </View>
                );
                let badgeType = data.badgeType ? data.badgeType : 'corner';
                if (badgeType == 'dot') {
                
                    let left = 0; let top = 0;

                    if (data.badge == '') {
                        top = -4; left = 6
                    } else if (data.badge.length == 1) {
                        top = -7; left = 4
                    } else if (data.badge.length == 2) {
                        top = -7; left = 2
                    } else if (data.badge.length >= 3) {
                        top = -7; left = -2
                    }

                    let badgePosition = { top: top, left: left };

                    if (data.badgePosition) {
                        badgePosition = data.badgePosition == 'leftTop' ? badgePosition : { top: top, right: left }
                    }

                    return (
                        <View style={{ width: this._columnWidth }} >
                            <TouchableHighlight underlayColor={'transparent'} activeOpacity={0.8} disabled={data.disabled ? data.disabled : false} onPress={typeof data.onPress == 'function' ? data.onPress : () => this._onPress(data, index)}>
                                <View>
                                    <View key={`cell-${(data.key != null) ? data.key : index}`} style={[cellStyles, cellStyle, { borderBottomWidth: borderBottom, borderLeftWidth: borderLeft, borderRightWidth: borderRight,paddingTop:titleImgPadding  }]}
                                    >
                                        <View>
                                            <Image source={data.icon} style={imageStyles} />
                                            <Badge type='dot' text={data.badge} fontStyle={data.badgeFontStyle} dotStyle={[{ position: 'absolute' }, badgePosition]} />
                                        </View>
                                        {title}
                                        {description}
                                    </View>
                                </View>
                            </TouchableHighlight>
                        </View>
                    );
                }  else if (badgeType == 'popover') {
                    let textStr = data.badge;
                    let leftPopver = 0;
                    if (data.badge.length > 4) {
                        textStr = data.badge.substring(0, 4);
                    }
                    if (data.badge.length == 1) {
                        leftPopver = 0
                    } else if (data.badge.length == 2) {
                        leftPopver = 5 
                    } else if (data.badge.length == 3) {
                        leftPopver = 15 -(imgWidth-26)/2
                    } else if (data.badge.length == 4) {
                        leftPopver = 25 -(imgWidth-26)/2
                    } else if (data.badge.length > 4) {
                        leftPopver = 25 -(imgWidth-26)/2
                    }
                    let badaePopverLeftPosition = { left: -leftPopver, top: -7 };
                    let badaePopverRightPosition = { right: -leftPopver, top: -7 }
                    return (
                        <View style={{ width: this._columnWidth}} >
                            <TouchableHighlight underlayColor={'transparent'} activeOpacity={0.8} disabled={data.disabled ? data.disabled : false} onPress={typeof data.onPress == 'function' ? data.onPress : () => this._onPress(data, index)}>
                                <View>
                                    <View key={`cell-${(data.key != null) ? data.key : index}`} style={[cellStyles, cellStyle, { borderBottomWidth: borderBottom, borderLeftWidth: borderLeft, borderRightWidth: borderRight,paddingTop:titleImgPadding },]}
                                    >
                                        <View>
                                            <Image source={data.icon} style={imageStyles} />
                                            {data.badgePosition == 'left' ?
                                                <Badge type='popverLeft' text={textStr} fontStyle={data.badgeFontStyle} dotStyle={[{ position: 'absolute' }, badaePopverLeftPosition]} /> :
                                                <Badge type='popverRight' text={textStr} fontStyle={data.badgeFontStyle} dotStyle={[{ position: 'absolute' }, badaePopverRightPosition]} />}
                                        </View>
                                        {title}
                                        {description}
                                    </View>
                                </View>
                            </TouchableHighlight>
                        </View>
                    );
                } else {
                    return (
                        <View style={{ borderWidth: 0.1, borderColor: 'transparent' }} key={`${(data.key != null) ? data.key : index}`} onLayout={(event) => this._cellLayout(event)}>
                            <Badge type='corner' text={data.badge} fontStyle={data.badgeFontStyle} badgePosition={data.badgePosition ? data.badgePosition : 'leftTop'} >
                                {badgeArea}
                            </Badge>
                        </View>
                    )
                }
            } else {
                return (
                    <View style={{ width: this._columnWidth }} key={`${(data.key != null) ? data.key : index}`} onLayout={(event) => this._cellLayout(event)}>
                        <TouchableHighlight underlayColor={'transparent'} activeOpacity={0.8} disabled={data.disabled ? data.disabled : false} onPress={typeof data.onPress == 'function' ? data.onPress : () => this._onPress(data, index)}>
                            <View>
                                <View key={`cell-${(data.key != null) ? data.key : index}`} style={[cellStyles, cellStyle, { borderBottomWidth: borderBottom, borderLeftWidth: borderLeft, borderRightWidth: borderRight ,paddingTop:titleImgPadding}]}>
                                    <Image source={data.icon} style={imageStyles} />
                                    {title}
                                    {description}
                                </View>
                            </View>
                        </TouchableHighlight>
                    </View>
                );
            }
        })
    }
}

Sudoku.propTypes = {
    rowWidth: PropTypes.number,
    //宫格列数
    columnCount: PropTypes.number.isRequired,
    //宫格行数
    rowCount: PropTypes.number,
    //宫格传入数据
    dataSource: PropTypes.array.isRequired,
    //宫格点击事件
    onPress: PropTypes.func,
    //是否有内边框
    hasInnerBorder: PropTypes.bool,
    //是否有外边框
    hasOuterBorder: PropTypes.bool,
    //是否有标题
    hasTitle: PropTypes.bool,
    //title是否只在一行显示
    singleTitle: PropTypes.bool,
    //是否有文字说明
    hasDescription: PropTypes.bool,
    //宫格内容是否横向排布
    isHorizontal: PropTypes.bool,
    //是否为可滑动样式
    slider: PropTypes.bool,
    //可滑动样式下圆点选中颜色
    dotActiveColor: PropTypes.string,
    //可滑动样式下圆点未选中颜色
    dotColor: PropTypes.string,
    //可滑动样式下自定义dot样式，
    dotStyle: PropTypes.object,
    //宫格高度
    cellHeight: PropTypes.number,
    //滑动页码指示器背景颜色
    sliderAreaBgColor: PropTypes.string,
    //宫格整体背景颜色
    bgColor: PropTypes.string,
    //图标样式自定义
    imageStyle: PropTypes.object,
    //边框颜色
    borderColor: PropTypes.string,
    //横排时，宫格高度
    rowHeight: PropTypes.number,
    //宫格自定义样式
    cellStyle: PropTypes.object
};

Sudoku.defaultProps = {
    columnCount: 3,
    rowCount: 2,
    data: [''],
    onPress: null,
    hasInnerBorder: true,
    hasOuterBorder: true,
    hasTitle: true,
    singleTitle: false,
    hasDescription: false,
    isHorizontal: false,
    slider: false,
    dotColor: '#D8D8D8',
    dotActiveColor: '#FF7B7B',
    cellHeight: 80,
    sliderAreaBgColor: 'transparent',
    bgColor: '#FFF',
    borderColor: Color.border,
    rowHeight: 44,
    dotStyle: {}
};




